/*

Copyright (c) 2004-2009 Krzysztof Ostrowski. All rights reserved.

Redistribution and use in source and binary forms,
with or without modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above
   copyright notice, this list of conditions and the following
   disclaimer in the documentation and/or other materials provided
   with the distribution.

THIS SOFTWARE IS PROVIDED "AS IS" BY THE ABOVE COPYRIGHT HOLDER(S)
AND ALL OTHER CONTRIBUTORS AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDER(S) OR ANY OTHER
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.

*/

#include "StdAfx.h"

#include "AsyncOutputPin.h"
#include "AsyncReader.h"

CAsyncOutputPin::CAsyncOutputPin(HRESULT * phr, CAsyncReader *pReader, CAsyncIo *pIo, CCritSec * pLock)
:	CBasePin(NAME("Async output pin"), pReader, pLock, phr, L"Output", PINDIR_OUTPUT), 
	m_pReader(pReader),
	m_pIo(pIo)
{
}

CAsyncOutputPin::~CAsyncOutputPin()
{
}

STDMETHODIMP CAsyncOutputPin::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
    CheckPointer(ppv,E_POINTER);

    if(riid == IID_IAsyncReader)
    {
        m_bQueriedForAsyncReader = TRUE;
        return GetInterface((IAsyncReader*) this, ppv);
    }
    else
        return CBasePin::NonDelegatingQueryInterface(riid, ppv);
}

STDMETHODIMP CAsyncOutputPin::Connect(IPin *pReceivePin, const AM_MEDIA_TYPE *pmt)
{
    return m_pReader->Connect(pReceivePin, pmt);
}

HRESULT CAsyncOutputPin::GetMediaType(int iPosition, CMediaType *pMediaType)
{
    if (iPosition < 0)
    {
        return E_INVALIDARG;
    }

    if (iPosition > 0)
    {
        return VFW_S_NO_MORE_ITEMS;
    }

    CheckPointer(pMediaType,E_POINTER); 
    CheckPointer(m_pReader,E_UNEXPECTED); 
    
    *pMediaType = *m_pReader->LoadType();

    return S_OK;
}


HRESULT CAsyncOutputPin::CheckMediaType(const CMediaType* pType)
{
    CAutoLock lck(m_pLock);

    if ((m_pReader->LoadType()->majortype == pType->majortype) &&
       (m_pReader->LoadType()->subtype == MEDIASUBTYPE_NULL ||
        m_pReader->LoadType()->subtype == pType->subtype))
    {
        return S_OK;
    }

    return S_FALSE;
}

HRESULT CAsyncOutputPin::CheckConnect(IPin *pPin)
{
    m_bQueriedForAsyncReader = FALSE;
    return CBasePin::CheckConnect(pPin);
}

HRESULT CAsyncOutputPin::CompleteConnect(IPin *pReceivePin)
{
    if (m_bQueriedForAsyncReader)
        return CBasePin::CompleteConnect(pReceivePin);
    else 
	{
#ifdef VFW_E_NO_TRANSPORT
        return VFW_E_NO_TRANSPORT;
#else
        return E_FAIL;
#endif
    }
}

HRESULT CAsyncOutputPin::BreakConnect()
{
    m_bQueriedForAsyncReader = FALSE;
    return CBasePin::BreakConnect();
}

HRESULT CAsyncOutputPin::InitAllocator(IMemAllocator **ppAlloc)
{
    CheckPointer(ppAlloc,E_POINTER);

    HRESULT hr = NOERROR;
    CMemAllocator *pMemObject = NULL;

    *ppAlloc = NULL;

    pMemObject = new CMemAllocator(NAME("Base memory allocator"), NULL, &hr);
    if (pMemObject == NULL)
    {
        return E_OUTOFMEMORY;
    }
    if (FAILED(hr))
    {
        delete pMemObject;
        return hr;
    }

    hr = pMemObject->QueryInterface(IID_IMemAllocator,(void **)ppAlloc);
    if (FAILED(hr))
    {
        delete pMemObject;
        return E_NOINTERFACE;
    }

    ASSERT(*ppAlloc != NULL);
    return NOERROR;
}


STDMETHODIMP CAsyncOutputPin::RequestAllocator(
	IMemAllocator* pPreferred, ALLOCATOR_PROPERTIES* pProps, IMemAllocator ** ppActual)
{
    CheckPointer(pPreferred,E_POINTER);
    CheckPointer(pProps,E_POINTER);
    CheckPointer(ppActual,E_POINTER);
    ASSERT(m_pIo);

    if (!pProps->cbAlign || !m_pIo->IsAligned(pProps->cbAlign))
    {
        m_pIo->Alignment(&pProps->cbAlign);
    }

    ALLOCATOR_PROPERTIES Actual;
    HRESULT hr;

    if (pPreferred)
    {
        hr = pPreferred->SetProperties(pProps, &Actual);

        if (SUCCEEDED(hr) && m_pIo->IsAligned(Actual.cbAlign))
        {
            pPreferred->AddRef();
            *ppActual = pPreferred;
            return S_OK;
        }
    }

    IMemAllocator* pAlloc;
    hr = InitAllocator(&pAlloc);
    if (FAILED(hr))
    {
        return hr;
    }

    hr = pAlloc->SetProperties(pProps, &Actual);
    if (SUCCEEDED(hr) && m_pIo->IsAligned(Actual.cbAlign))
    {
        *ppActual = pAlloc;
        return S_OK;
    }

    pAlloc->Release();

    if (SUCCEEDED(hr))
    {
        hr = VFW_E_BADALIGN;
    }
    return hr;
}

STDMETHODIMP CAsyncOutputPin::Request(IMediaSample* pSample, DWORD_PTR dwUser)
{
    CheckPointer(pSample,E_POINTER);

    REFERENCE_TIME tStart, tStop;
    HRESULT hr = pSample->GetTime(&tStart, &tStop);
    if (FAILED(hr))
    {
        return hr;
    }

    LONGLONG llPos = tStart / UNITS;
    LONG lLength = (LONG) ((tStop - tStart) / UNITS);

    LONGLONG llTotal=0, llAvailable=0;

    hr = m_pIo->Length(&llTotal, &llAvailable);
    if (llPos + lLength > llTotal)
    {
        LONG lAlign;
        m_pIo->Alignment(&lAlign);

        llTotal = (llTotal + lAlign -1) & ~(lAlign-1);

        if (llPos + lLength > llTotal)
        {
            lLength = (LONG) (llTotal - llPos);

            ASSERT((llTotal * UNITS) <= tStop);
            tStop = llTotal * UNITS;
            pSample->SetTime(&tStart, &tStop);
        }
    }

    BYTE* pBuffer;
    hr = pSample->GetPointer(&pBuffer);
    if (FAILED(hr))
    {
        return hr;
    }

    return m_pIo->Request(llPos, lLength, TRUE, pBuffer, (LPVOID) pSample, dwUser);
}

STDMETHODIMP CAsyncOutputPin::WaitForNext(DWORD dwTimeout, IMediaSample** ppSample, DWORD_PTR * pdwUser)
{
    CheckPointer(ppSample,E_POINTER);

    LONG cbActual;
    IMediaSample* pSample=0;

    HRESULT hr = m_pIo->WaitForNext(dwTimeout, (LPVOID*) &pSample, pdwUser, &cbActual);

    if (SUCCEEDED(hr))
    {
        pSample->SetActualDataLength(cbActual);
    }

    *ppSample = pSample;
    return hr;
}

STDMETHODIMP CAsyncOutputPin::SyncReadAligned(IMediaSample* pSample)
{
    CheckPointer(pSample,E_POINTER);

    REFERENCE_TIME tStart, tStop;
    HRESULT hr = pSample->GetTime(&tStart, &tStop);
    if (FAILED(hr))
    {
        return hr;
    }

    LONGLONG llPos = tStart / UNITS;
    LONG lLength = (LONG) ((tStop - tStart) / UNITS);

    LONGLONG llTotal;
    LONGLONG llAvailable;

    hr = m_pIo->Length(&llTotal, &llAvailable);
    if (llPos + lLength > llTotal)
    {
        LONG lAlign;
        m_pIo->Alignment(&lAlign);

        llTotal = (llTotal + lAlign -1) & ~(lAlign-1);

        if (llPos + lLength > llTotal)
        {
            lLength = (LONG) (llTotal - llPos);

            ASSERT((llTotal * UNITS) <= tStop);
            tStop = llTotal * UNITS;
            pSample->SetTime(&tStart, &tStop);
        }
    }

    BYTE* pBuffer;
    hr = pSample->GetPointer(&pBuffer);
    if (FAILED(hr))
    {
        return hr;
    }

    LONG cbActual;
    hr = m_pIo->SyncReadAligned(llPos, lLength, pBuffer, &cbActual, pSample);

    pSample->SetActualDataLength(cbActual);
    return hr;
}

STDMETHODIMP CAsyncOutputPin::SyncRead(LONGLONG llPosition, LONG lLength, BYTE* pBuffer)
{
    return m_pIo->SyncRead(llPosition, lLength, pBuffer);
}

STDMETHODIMP CAsyncOutputPin::Length(LONGLONG* pTotal, LONGLONG* pAvailable)
{
    return m_pIo->Length(pTotal, pAvailable);
}

STDMETHODIMP CAsyncOutputPin::BeginFlush()
{
    return m_pIo->BeginFlush();
}


STDMETHODIMP CAsyncOutputPin::EndFlush()
{
    return m_pIo->EndFlush();
}
